package com.heima.article.service.impl;

import com.alibaba.fastjson.JSON;
import com.heima.apis.wemedia.IWemediaClient;
import com.heima.article.mapper.ApArticleMapper;
import com.heima.article.service.HotArticleService;
import com.heima.common.constatns.ArticleConstants;
import com.heima.common.redis.CacheService;
import com.heima.model.article.pojos.ApArticle;
import com.heima.model.article.vos.HotArticleVo;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.wemedia.pojos.WmChannel;
import lombok.extern.slf4j.Slf4j;
import org.joda.time.DateTime;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.function.Predicate;
import java.util.stream.Collectors;


@Slf4j
@Transactional
@Service
public class HotArticleServiceImpl implements HotArticleService {

    @Autowired
    private ApArticleMapper apArticleMapper;

    @Autowired
    private IWemediaClient iWemediaClient;

    @Autowired
    private CacheService cacheService;

    /**
     * 计算热点文章
     */
    @Override
    public void computeHotArticle() {

        //5天前的时间
        Date date = DateTime.now().minusDays(5).toDate();

        //查询前5天的文章数据
        List<ApArticle> articleList = apArticleMapper.findArticleListByLast5Day(date);

        //计算文章分值
        List<HotArticleVo> hotArticleVoList = computeHotArticleScore(articleList);

        //为每个频道缓存30条分值较高的文章
        cacheTagTORedis(hotArticleVoList);
    }


    /**
     * 为每个频道缓存30条分值较高的文章
     *
     * @param hotArticleVoList
     */
    private void cacheTagTORedis(List<HotArticleVo> hotArticleVoList) {
        //为每个频道缓存30条分值较高的文章
        ResponseResult responseResult = iWemediaClient.getChannels();
        if (responseResult.getCode().equals(200)) {
            String string = JSON.toJSONString(responseResult.getData());
            List<WmChannel> wmChannels = JSON.parseArray(string, WmChannel.class);
            //检索出每个频道的文章
            if (wmChannels != null && wmChannels.size() > 0) {
                for (WmChannel wmChannel : wmChannels) {

                    List<HotArticleVo> hotArticleVos = hotArticleVoList.stream()
                            .filter(item -> item.getChannelId().equals(wmChannel.getId()))
                            .collect(Collectors.toList());
                    //给文章进行排序 然后去分值较高的30条数据
                    sortAndCache(hotArticleVos, ArticleConstants.HOT_ARTICLE_FIRST_PAGE + wmChannel.getId());
                }
            }
        }
        //设置推荐数据
        sortAndCache(hotArticleVoList, ArticleConstants.HOT_ARTICLE_FIRST_PAGE + ArticleConstants.DEFAULT_TAG);
    }


    /**
     * 给文章进行排序 然后缓存分值较高的30条数据
     * @param hotArticleVos
     * @param key
     */
    private void sortAndCache(List<HotArticleVo> hotArticleVos, String key) {
        hotArticleVos = hotArticleVos.stream()
                .sorted(Comparator.comparing(HotArticleVo::getScore).reversed())
                .collect(Collectors.toList());
        //每个频道只要30条数据
        if (hotArticleVos.size()>30){
            hotArticleVos = hotArticleVos.subList(0,30);
        }
        //放入缓存
        cacheService.set(key,JSON.toJSONString(hotArticleVos));
    }

    /**
     * 计算文章分值
     *
     * @param articleList
     * @return
     */
    private List<HotArticleVo> computeHotArticleScore(List<ApArticle> articleList) {

        List<HotArticleVo> list = new ArrayList<>();

        if (articleList != null && articleList.size() > 0) {
            for (ApArticle apArticle : articleList) {
                HotArticleVo hotArticleVo = new HotArticleVo();
                BeanUtils.copyProperties(apArticle, hotArticleVo);
                Integer score = computeBehaviorConstants(apArticle);
                hotArticleVo.setScore(score);

                list.add(hotArticleVo);
            }
        }
        return list;
    }

    /**
     * 计算文章的具体分值
     *
     * @param apArticle
     * @return
     */
    private Integer computeBehaviorConstants(ApArticle apArticle) {

        Integer scere = 0;
        if (apArticle.getLikes() != null) {
            scere += apArticle.getLikes() * ArticleConstants.HOT_ARTICLE_LIKE_WEIGHT;
        }
        if (apArticle.getViews() != null) {
            scere += apArticle.getViews() * ArticleConstants.HOT_ARTICLE_READ_WEIGHT;
        }
        if (apArticle.getComment() != null) {
            scere += apArticle.getComment() * ArticleConstants.HOT_ARTICLE_COMMENT_WEIGHT;
        }
        if (apArticle.getCollection() != null) {
            scere += apArticle.getCollection() * ArticleConstants.HOT_ARTICLE_COLLECTION_WEIGHT;
        }
        return scere;
    }


}
